package com.coder520.controller;

import com.coder520.common.Const;
import com.coder520.common.ServerResponse;
import com.coder520.pojo.User;
import com.coder520.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 * Created by ASUS on 2017/7/4.
 */
@Controller
@RequestMapping("/user")
public class UserController {


    @Autowired
    private IUserService iUserService;

    @RequestMapping("/login")
    /**
     * 跳转登录页面
     */
    public String login(){
        return "login";

    }

    /**
     * 跳转主页面
     * @return
     */
    @RequestMapping("/home")
    public String index(){
        return "home";
    }

    @RequestMapping("/checkUser")
    @ResponseBody
    public ServerResponse<User> checkUser(HttpSession session, String username, String password) throws UnsupportedEncodingException, NoSuchAlgorithmException {

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();

//        User user = iUserService.checkUser(username,password);

        subject.login(usernamePasswordToken);
        SecurityUtils.getSubject().getSession().setTimeout(1800000);

//        if(user==null){
//            return ServerResponse.createByError("用户名或密码错误");
//        }
//        session.setAttribute(Const.CURRENT_USER,user);

        User user = getUser(session);

        return ServerResponse.createBySuccess(user);
    }

    /**
     * 获取用户信息
     * @param session
     * @return
     */
    @RequestMapping("/getUser")
    @ResponseBody
    public User getUser(HttpSession session){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        return user;
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute(Const.CURRENT_USER);
        return "login";
    }


    @RequestMapping("/regist")
    public void regist(User user) throws UnsupportedEncodingException, NoSuchAlgorithmException {

        iUserService.regist(user);
    }


}
